//
//  PhotoView.m
//  SinaWebo
//
//  Created by 亦心 on 15/4/3.
//  Copyright (c) 2015年 亦心. All rights reserved.
//

#import "PhotoView.h"
#import "UIImageView+WebCache.h"
#import "UIImage+GIF.h"
#import "PicMetadata.h"

@interface PhotoView ()
@property (nonatomic, weak) UIImageView *gifView;
@end

@implementation PhotoView
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self initView];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder{
    self=[super initWithCoder:coder];
    if (self) {
        [self initView];
    }
    return self;
}

-(void)initView{
    // 添加一个GIF小图片
    UIImage *image = [UIImage imageNamed:@"timeline_image_gif"];
    UIImageView *gifView = [[UIImageView alloc] initWithImage:image];
    [self addSubview:gifView];
    self.gifView=gifView;
    self.clipsToBounds = YES;
    self.contentMode = UIViewContentModeScaleAspectFill;
}


- (void)setPicInfo:(PicInfo *)picInfo{
    _picInfo = picInfo;
    // 控制gifView的可见性
    self.gifView.hidden = NO;
    PicMetadata *middle = picInfo.bmiddle;
    if (picInfo.badgeType == PictureBadgeTypeLong) {
        self.gifView.image = [UIImage imageNamed:@"timeline_image_longimage"];
    }else if([middle.type isEqualToString:@"GIF"]){
        self.gifView.image = [UIImage imageNamed:@"timeline_image_gif"];
    }else{
        self.gifView.hidden = YES;
    }
    NSString *url = [middle.url stringByReplacingOccurrencesOfString:@"or360" withString:@"bmiddle"];
    [self sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:nil options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        picInfo.progress = 1.0 * receivedSize / expectedSize;
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (picInfo.badgeType == PictureBadgeTypeLong) {
            UIGraphicsBeginImageContextWithOptions(CGSizeMake(picInfo.scalWith, picInfo.scalHeight), NO, 0.0);
            CGFloat with = picInfo.scalWith;
            CGFloat height = image.size.height * (picInfo.scalWith / image.size.width);
            [image drawInRect:CGRectMake(0, 0, with, height)];
            UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            self.image = newImage;
        }else if ([imageURL.absoluteString  hasSuffix:@"gif"]){
            self.image = image.images.firstObject;
        }
        
    }];
}

-(void)setPhoto:(Photo *)photo{
    _photo=photo;
    
}


-(void)layoutSubviews{
    [super layoutSubviews];
    self.gifView.layer.anchorPoint=CGPointMake(1, 1);
    self.gifView.layer.position=CGPointMake(self.frame.size.width, self.frame.size.height);
}
@end
